package com.zzzs.threaddemo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

import static java.util.concurrent.Executors.newCachedThreadPool;

/**
 * @author zhu_shuai
 * @since 2021/6/23
 */
public class ExecutorDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = newCachedThreadPool();  // 无边界线程池，具有自动线程回收
        // ExecutorService executorService = newFixedThreadPool(10); // 固定大小的线程池
        // ExecutorService executorService = newSingleThreadExecutor(); //单个后台线程
        // ScheduledExecutorService scheduledExecutorService = newScheduledThreadPool();  // 延期执行
        // new ThreadPoolExecutor();  自定义线程池
        List<Future> futureList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            // 1. Runable 执行线程
            // executorService.execute(new MyRunable(i));

            // 2. Runable 执行线程, 返回值为null
            // Future<?> submit = executorService.submit(new MyRunable(i));
            // futureList.add(submit);

            // 3. Callable 执行线程，获取返回值
            Future submit1 = executorService.submit(new MyCallable(i));
            futureList.add(submit1);
        }
        executorService.shutdown();
        for (Future future : futureList) {
            System.out.println(future.get());
        }
    }

}
